guice整合guice-servlet,web scope注解 <6>

guice整合guice-servlet,web scope注解 <6>

guice servlet提供了几个比较有用的web scope,类似与传统servlet
的session,request这些提供的范围等。

guice servlet 提供的web scope 如下:

  • @RequestScoped
  • @SessionScoped
  • @RequestParameters

1.@RequestScoped

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package cn.northpark.action;

import com.google.inject.servlet.RequestScoped;

/**
* 类似我们请求的时候将值保存在此访问之中
* @author bruce
*
*/
@RequestScoped
public class RequstScope {


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package cn.northpark.action;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class RequstScopeTest {

@Inject
private Provider<RequstScope> requst=null;


RequstScope a=requst.get();//通过此种方法去取此范围的值

}

2.@SessionScoped

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package cn.northpark.action;

import com.google.inject.servlet.SessionScoped;

@SessionScoped
public class SessionScope {

private int count=0;

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package cn.northpark.action;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class SessionScopeTest {

@Inject
private Provider<SessionScope> session=null;


SessionScope a=session.get();//通过此种方法去取此范围的值

void test(){
a.setCount(2);
}
}

3.@RequestParameters

例子如下:

1
2
3
@Inject
@RequestParameters
private Provider<Map<String, String[]>> reqParamMapProvider;

guice servlet 还是比较好用,如果你选择用servlet开发的时候建议用它了。

生活不止苟且,还有我喜爱的海岸.